<?php

namespace app\common\model;

use think\Model;

class Formwork extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 定义字段类型
    protected $type = [
    ];
    protected $append = [
        'sale',
        'addon'
    ];

    /**
     * 计算显示销量 (初始销量 + 实际销量)
     */
    public function getSaleAttr($value, $data)
    {
        return (int)$data['sale_initial'] + (int)$data['sale_actual'];
    }

    /**
     * 获取模板插件信息
     */
    public function getAddonAttr($value, $data)
    {
        $addon = get_addon_info($data['name']);
        return isset($addon['title'])?$addon['title']:'--';
    }

    /**
     * 关联版本表
     */
    public function version()
    {
        return $this->hasOne('app\\common\\model\\FormworkVersion','formwork_id','id')->where('show',1)->order(['id' => 'asc']);//最新版本
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    /**
     * 获取模板列表
     */
    public function getList($status = -1 ,$order = 'default')
    {
        // 筛选条件
        $filter = [];
        $status > -1 && $filter['status'] = $status;
        $order == 'default' && $sort = ['weigh' => 'desc','id' => 'desc'];
        $order == 'sale' && $sort = ['sale_actual' => 'desc'];
        $order == 'createtime' && $sort = ['createtime' => 'desc'];
        $order == 'updatetime' && $sort = ['updatetime' => 'desc'];
        // 执行查询
        return $this->with(['version'])
            ->where($filter)
            ->order($sort)
            ->select();
    }

    /**
     * 获取模板列表
     */
    public function getApiList()
    {
        // 执行查询
        return $this->order('id','desc')->select();
    }

    /**
     * 获取详情
     */
    public static function detail($id)
    {
        return self::get($id,['version']);
    }
}
